package com.siki.config.filterConfig.loginStatus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siki.mapper.UserMapper;
import com.siki.pojo.commonEntity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * 权限判断实现类
 *
 * @Author Siki
 * @Date 2020/6/5
 */
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        QueryWrapper<SysUser> SysUserWrapper = new QueryWrapper<>();
        SysUserWrapper.eq("account",username);
        SysUser sysUser = userMapper.selectOne(SysUserWrapper);
        if (sysUser == null) {
            throw new RuntimeException("账号不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_admin"));
//        if (sysUser != null) {
//            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysUser.getUserRole().getName());
//            grantedAuthorities.add(grantedAuthority);
//        }
        return new User(sysUser.getId(),sysUser.getPassword(),grantedAuthorities);
    }

}
